//
//  CitySearchResultViewController.m
//  MeiTuan
//
//  Created by Ansen on 15-3-10.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "CitySearchResultViewController.h"
#import "City.h"
#import "MJExtension.h"
#import "Const.h"

@interface CitySearchResultViewController ()

@property (nonatomic, strong) NSArray *cities;
@property (nonatomic, strong) NSArray *resultCities;

@end

@implementation CitySearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(NSArray *)cities
{
    if (!_cities) {
        self.cities = [City objectArrayWithFilename:@"cities.plist"];
    }
    return _cities;
}


-(void)setSearchText:(NSString *)searchText
{
    _searchText = [searchText copy];
    
    searchText = searchText.lowercaseString;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@ or pinYin contains %@ or pinYinHead contains %@", searchText, searchText, searchText];
    self.resultCities = [self.cities filteredArrayUsingPredicate:predicate];
    
    [self.tableView reloadData];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectio{

    return self.resultCities.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID = @"city";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    City *city = self.resultCities[indexPath.row];
    cell.textLabel.text = city.name;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    City *city = self.resultCities[indexPath.row];
    [NotificationCenter postNotificationName:CityDidChangeNotification object:nil userInfo:@{SelectCityName:city.name}];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

@end
